import { history } from 'umi'
import type { History } from 'umi'
import { stores } from '@/stores'

/** 需要根据权限，来区分的路由 */
const needRolePath = ['/home']

/** 格式化路由，【原路由】加上【角色权限字符串】 */
const formatterPath = (path: string): string => {
    const {
        isTeacherRole,
        isAdminRole,
        isCenterRole,
        isProvinceRole,
        isStudentRole,
    } = stores.userStore

    if (needRolePath.includes(path)) {
        let roleName = ''
        if (isTeacherRole) {
            roleName = 'trainer'
        } else if (isCenterRole) {
            roleName = 'manager'
        } else if (isAdminRole) {
            roleName = 'manager'
        } else if (isProvinceRole) {
            roleName = 'manager'
        } else if (isStudentRole) {
            roleName = 'manager'
        }

        let firstStr = path.charAt(1).toLocaleUpperCase()
        return roleName + firstStr + path.slice(2, path.length)
    }
    return path
}

type Method = 'push' | 'replace'
type Wrap = History[Method]

/** 根据权限的路由跳转。 */
export const roleHistory = (() => {
    const getHistoryMethod = (method: Method) => {
        /** 包装push和replace方法。使用{@link formatterPath}修改path属性 */

        const wrap: Wrap = (...args) => {
            const [path, state] = args

            // 方法的两种重写方式
            if (typeof path === 'string') {
                const _path = formatterPath(path)
                history[method](_path, state)
            } else {
                const _path = path.pathname ? formatterPath(path.pathname) : undefined
                history[method]({ ...path, pathname: _path })
            }
        }

        return wrap
    }

    const wrapHistory: History = {
        ...history,
        push: getHistoryMethod('push'),
        replace: getHistoryMethod('replace'),
    }

    return wrapHistory
})()
